<template>
  <div class="detail-box">
    <task-map
      mode="display"
      :node-state-styles="nodeStateStyles"
      v-model="collaborationTask.subTasks"
      :node-states="nodeStates"
      :get-node-label="getNodeLabel"
      :click-menu-config="clickMenuConfig"
    ></task-map>
    <task-detail-table
      :form="taskDetail"
    >
    </task-detail-table>
    <device-requirements-view
      v-model="deviceRequirement"
    >
    </device-requirements-view>

    <el-row type="flex" justify="center">
      <el-col :span="8">
        <el-button type="warning" @click="handleGetApp()">
          下载待测应用
        </el-button>
      </el-col>
      <el-col :span="8">
        <el-button type="success" @click="handleGetDoc()">
          下载测试文档
        </el-button>
      </el-col>
      <el-col :span="8">
        <el-button v-if="isReportSubmitted" type="primary" @click="handleCheckReport">
          查看报告
        </el-button>
        <el-button v-else id="get-task-btn" type="primary" @click="submitDialogVisible = true">
          提交报告
        </el-button>
      </el-col>
    </el-row>
    <el-dialog :visible.sync="submitDialogVisible">
      <submit-report-component
          @submitted="handleSubmitReport"
          :get-task-id="() => taskDetail.id"
          :submit-report="submitReport"
      ></submit-report-component>
    </el-dialog>
    <el-dialog :visible.sync="sendMessageDialogVisible" :title="messageBoxTitle">
      <el-form>
        <el-form-item>
          <el-input type="textarea" v-model="messageContent"></el-input>

          <el-button style="margin-top: 30px" @click="handleSendMessage">发送</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>

</template>

<script>
import TaskMap from "@/components/new/task-map/TaskMap";
import TaskDetail from "@/components/worker/plaza/taskDetail/TaskDetail";
import TaskDetailTable from "@/components/new/task-detail-table/TaskDetailTable";
import DeviceRequirementsView from "@/components/new/device-requirements-card/DeviceRequirementsView";
import {getCollaborationTaskDetail, getCollaborationTaskMyGroup, getTaskFile} from "@/api/task";
import {Debounce} from "@/utils/Debounce";
import {downloadFile} from "@/api/file";
import SubmitReportComponent from "@/components/new/submit-report/SubmitReportComponent";
import {sendMessage} from "@/api/user";
import {createCollaborationTaskReport} from "@/api/report";
export default {
  name: "ExecutingCollaborationTask",
  components: {SubmitReportComponent, DeviceRequirementsView, TaskDetailTable, TaskDetail, TaskMap},
  methods: {
    handleGetApp: Debounce(function () {
      this.$message('正在下载待测应用……');
      const taskId = this.$route.params.taskid;
      let url = null;
      const data = {
        taskId: taskId,
        kind: "2"
      }
      getTaskFile(data).then(res => {
        url = res.name
        downloadFile(url).then(res => {
        })
      });
    }, 1000),


    handleGetDoc: Debounce(function () {
      this.$message('正在下载测试文档……');
      const taskId = this.$route.params.taskid;
      let url = null;
      const data = {
        taskId: taskId,
        kind: "3"
      }
      getTaskFile(data).then(res => {
        url = res.name
        downloadFile(url).then(res => {
        })
      });
    }, 1000),

    handleSubmitReport(){
      this.submitDialogVisible = false;
      this.loadAll();
    },

    handleCheckReport(){
      const target = this.taskGroupMap.get(this.taskDetail.id);
      this.$router.push({
        path: '/worker/mytasks/collaborationTask/reportDetail',
        query: {
          reportid: target.reportId,
          taskid: target.taskId
        }
      })
    },

    loadAll(){

      getCollaborationTaskMyGroup(this.$route.params.taskid, sessionStorage.getItem('userid'))
          .then(res => {
            if(res.code === 200){
              this.taskGroup = res.data;
            }else{
              throw new Error(res.msg);
            }
          })
          .then(() => getCollaborationTaskDetail(this.$route.params.taskid))
          .then(res => {
            if(res.code === 200){
              this.collaborationTask = res.data;
            }else {
              throw new Error(res.msg);
            }
          })
          .catch(e => {
            this.$message.error(e.message);
          })
    },
    handleSendMessage(){
      sendMessage({
        sourceUserId: Number.parseInt(sessionStorage.getItem('userid')),
        targetUserId: this.messageTarget.workerId,
        relatedSubTaskId: this.messageTarget.taskId,
        messageContent: `${this.messageContent}(来自 ${sessionStorage.getItem('email')})`
      }).then(res => {
        if(res.code === 200){
          this.sendMessageDialogVisible = false;
          this.$message.success(res.msg);
        }else{
          throw new Error(res.message);
        }
      }).catch(e => {
        this.$message.error(e.message);
      })
    }
  },
  data() {
    return {
      nodeStateStyles: {
        myTask: {
          stroke: '#ff7900',
          fill: '#f1a36a'
        }
      },
      collaborationTask: {},
      taskGroup: [],
      submitDialogVisible: false,
      sendMessageDialogVisible: false,
      taskGroupMap: undefined,
      messageContent: '',
      messageTarget: {}

    }
  },
  computed: {
    submitReport(){
      return createCollaborationTaskReport;
    },
    taskDetail(){
      if(this.collaborationTask.subTasks){
        const myGroup = this.taskGroup.filter(g => g.workerId === Number.parseInt(sessionStorage.getItem('userid')))[0];
        if(myGroup){
          const task = this.collaborationTask.subTasks.filter(task => task.id === myGroup.taskId)[0];
          task.username = this.collaborationTask.username;
          return task;
        }
      }
    },
    deviceRequirement(){
      if(this.taskDetail){
        return this.taskDetail.deviceRequirement;
      }
    },
    nodeStates(){
      if(this.taskDetail){
        return {
          myTask:  new Set([this.taskDetail.id])
        }
      }
    },
    getNodeLabel(){
      return node => {
        if(this.taskGroupMap.get(node.id)){
          return this.taskGroupMap.get(node.id).workerName;
        }
      }
    },
    isReportSubmitted(){
      if(this.taskGroupMap && this.taskDetail){
        return this.taskGroupMap.get(this.taskDetail.id).reportId !== 0;
      }
    },
    clickMenuConfig(){
      return {
        getContent: (task) => {
          if(this.taskGroupMap.get(task.id)){
            return `
          <div>
            <button class="collaboration-task-detail-click-menu-button send-msg">发送消息</button>
            <button class="collaboration-task-detail-click-menu-button check-work">查看工作</button>
          </div>
          `
          }
        },
        handleMenuClick: (target, task) => {
          if(target.classList.contains('send-msg')){
            this.messageTarget = this.taskGroupMap.get(task.id);
            this.sendMessageDialogVisible = true;
          }
          else if(target.classList.contains('check-work')){
            const reportid = this.messageTarget.reportId;
            if(reportid){
              this.$router.push({
                path: '/worker/mytasks/collaborationTask/reportDetail',
                query: {
                  reportid,
                  taskid: this.messageTarget.taskId
                }
              })
            }

          }
        }
      }
    },
    messageBoxTitle(){
      return `向${this.messageTarget.workerName}发送消息`
    },

  },
  mounted() {
    this.loadAll();
  },
  watch: {
    taskGroup(newVal){
      const m = new Map();
      newVal.forEach(g => {
        m.set(g.taskId, g);
      });
      this.taskGroupMap = m;
    }
  }
}
</script>

<style>
.collaboration-task-detail-click-menu-button{
  border-style: none;
  padding: 2px 5px;
  background-color: dodgerblue;
  color: white;
  border-radius: 5px;
}
</style>
